<template>
  <div class="q-gutter-y-md">
    <q-table
      class="card-radius my-table"
      wrap-cells
      flat
      bordered
      :columns="columns"
      :rows="rows"
      :pagination="{ rowsPerPage: 15 }"
      :filter="filter"
      row-key="id"
      no-data-label="No data found."
      no-results-label="The filter didn't uncover any results"
    >
      <!-- <template v-slot:top-row="props">
            <ColsFilter :filter="props.cols" ref="colsFilter"></ColsFilter>
          </template> -->
      <template v-slot:top>
        <div class="row justify-between" style="width: 100%">
          <div class="fal page-header">
            {{ props.groupname }} - Competence Settings

            <!-- <q-select
              style="width: 250px"
              borderless
              v-model="groupname"
              input-debounce="0"
              hide-bottom-space
              lazy-rules
              @filter="groupFilterFn"
              :options="groupOptions"
              :dense="true"
              use-input
              class="input-css q-mx-md"
            >
            </q-select> -->
          </div>
          <div>
            <q-card-actions>
              <q-input
                  borderless
                  dense
                  filled
                  debounce="300"
                  v-model="filter"
                  placeholder="Username"
                  class="q-mx-md"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>
              <q-btn
                dense
                round
                flat
                label="Save"
                class="yellow-btn"
                icon="save"
                @click="bulkSave"
              ></q-btn>
              <q-btn
                dense
                round
                flat
                label="Add"
                class="default-btn"
                icon="add"
                @click="AddRow"
              ></q-btn>
            </q-card-actions>
          </div>
        </div>
      </template>
      <template v-slot:body-cell-username="props">
        <q-td>
          <q-select
            borderless
            v-model="props.row.username"
            input-debounce="0"
            hide-bottom-space
            lazy-rules
            @filter="userFilterFn"
            :options="userOptions"
            :dense="true"
            use-input
            :readonly="props.row.mode !== 'edit'"
          >
          </q-select>
        </q-td>
      </template>

      <template v-slot:body-cell-expiry_date="props">
        <q-td key="expiry_date" :props="props">
          {{ props.value }}
          <q-popup-edit buttons label-set="Save" v-model="props.row.expiry_date" v-slot="scope">
            <q-input
              :rules="[(val) => dateRule(val)]"
              v-model="scope.value"
              dense
              autofocus
              counter
              @keyup.enter="scope.set"
            />
          </q-popup-edit>
        </q-td>
      </template>

      <template v-slot:body-cell-enable="props">
        <q-td>
          <q-checkbox v-model="props.row.enable" />
        </q-td>
      </template>

      <template v-slot:body-cell-actions="props">
        <q-td>
          <div class="text-left">
            <!-- <q-btn
                  dense
                  round
                  flat
                  class="edit-btn"
                  @click="create(props.row)"
                  icon="save"
                ></q-btn> -->
            <q-btn
              dense
              round
              flat
              class="del-btn"
              @click="deleteFn(props.row.id, props.row.username)"
              icon="delete"
            ></q-btn>
          </div>
        </q-td>
      </template>

      <template v-slot:no-data="{ icon, message }">
        <div class="full-width row flex-center text-accent q-gutter-sm">
          <!-- <q-icon size="2em" name="sentiment_dissatisfied" /> -->
          <q-icon size="2em" :name="icon" />
          <span> {{ message }} </span>
        </div>
      </template>
    </q-table>
  </div>
</template>

<script setup lang="ts">
import { useQuasar } from 'quasar';
import {
  bulkUpdateGroupSetting,
  deleteGroupSetting,
  getGroupSettingOptions,
  listGroupSetting,
} from 'src/services/groupSettingService';
import { GroupSetting } from 'src/services/type';
import { computed, onMounted, ref, watch } from 'vue';
import dateIcon from 'src/assets/style/date.png';
import ColsFilter from 'src/components/table/ColsFilter.vue';
import { formatDate, formatDateTimeString } from 'src/utils/dateUtils';

import { color } from 'echarts';

const props = defineProps<{
  groupname: string
}>()

const align = 'left';
const columns = [
  // {
  //   name: 'id',
  //   label: '#',
  //   field: 'id',
  //   sortable: true,
  //   align,
  //   search: false,
  //   style: 'width: 100px !important',
  //   headerStyle: 'width: 100px !important',
  // },
  {
    name: 'username',
    label: 'Username',
    field: 'username',
    sortable: true,
    align,
  },
  // {
  //   name: 'groupname',
  //   label: 'Course Code',
  //   field: 'groupname',
  //   sortable: true,
  //   align,
  // },
  {
    name: 'expiry_date',
    label: 'End Date',
    field: 'expiry_date',
    sortable: true,
    align,
  },
  {
    name: 'enable',
    label: 'Enable',
    field: 'enable',
    sortable: true,
    align,
  },
  {
    name: 'actions',
    label: 'Actions',
    field: 'actions',
    sortable: true,
    align,
  },
];

const $q = useQuasar();

const colsFilter = ref<typeof ColsFilter>();

const userOptions = ref<string[]>([]);
const groupOptions = ref<string[]>([]);

const userArr = ref<string[]>([]);
const groupArr = ref<string[]>([]);

const filter = ref('')

const date = ref(formatDate(new Date()));

const rows = ref<GroupSetting[]>([]);


async function init() {
  if (props.groupname){
    const res = await listGroupSetting(props.groupname);
    console.log(res);
    
    maxId.value = res.max_id;
    rows.value = res.data;
  }
}

// function filterFn(row: GroupSetting) {
//   if (colsFilter.value) {
//     return colsFilter.value.filterFn(row);
//   }
// }

// const filterRows = computed(() => {
//   return rows.value.filter(filterFn);
// });

const maxId = ref(0);

const pending = ref<number[]>([])

function AddRow() {
  const index = (maxId.value += 1);
  console.log(index);
  pending.value.push(index)
  const row = {
    id: index,
    enable: true,
    expiry_date: date.value,
    groupname: props.groupname,
    username: '',
    mode: 'edit',
  };
  rows.value = [row, ...rows.value.slice(0, index)];
}

async function bulkSave() {
  console.log(rows.value);
  const res = await bulkUpdateGroupSetting(rows.value);
  if (res) {
    $q.notify({
      message: 'success',
      color: 'positive',
    });
    initData();
  }
}

function deleteFn(id: number, username: string) {
  $q.dialog({
    title: 'Confirm',
    message: 'Are you sure to delete this record?',
    cancel: true,
  }).onOk(async () => {
    rows.value = [...rows.value.filter((item) => item.id != id)];
    console.log(pending.value);
    
    if (!pending.value.includes(id)){
      await deleteGroupSetting(id, username);
      $q.notify({
        message: 'success',
        color: 'positive',
      });
      initData()
    }
  });
}

function dateRule(val: string) {
  if (val == '') {
    return;
  }
  const regex = /^\d{4}-\d{2}-\d{2}$/;
  return regex.test(val) || 'Date must be in the format "YYYY-MM-DD"';
}

async function initSettingOptions() {
  if (props.groupname){
    const res = await getGroupSettingOptions(props.groupname);
    
    userOptions.value = res.username;
    userArr.value = res.username;
  }
}

function userFilterFn(val: string, update: any) {
  if (val === '') {
    update(() => {
      userOptions.value = [...userArr.value];
    });
    return;
  }

  update(() => {
    const needle = val.toLowerCase();
    userOptions.value = userArr.value.filter(
      (v: string) => v.toLowerCase().indexOf(needle) > -1
    );
  });
}


async function initData() {
  pending.value = []
   await initSettingOptions();
   await init();
}

 function manualUpdate(){
   initData()
}

defineExpose({
  manualUpdate,
})

onMounted(() => {
  initData()
})


</script>
